package com.lvan.controller.util;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


/**
 * spring mvc 上传文件
 * @author lvan
 * 2013-6-26
 *
 */
public class SpringMvcUploadFile {

	/**
	 * 上传文件
	 * @param fileUpload 文件名称
	 */
	@RequestMapping(value="/upload" , method = RequestMethod.POST)
	public void upload(HttpServletRequest request, @RequestParam("fileUpload") MultipartFile fileUpload){
		 /**
		  * 判断是否有文件
		  */
		 if (!fileUpload.isEmpty()) {
	        try {
					String fileName = fileUpload.getOriginalFilename();
					/**
					 * 获取文件后缀
					 */
					String[] suffixs=fileName.split("\\.");
					String suffix = "."+suffixs[suffixs.length-1];
					
					/**
					 * 判断上传的文件格式是否正确
					 */
					if((".zip.rar.gz.tar.bz2".indexOf(suffix.toLowerCase())!=-1)){
						byte[] bytes = fileUpload.getBytes();
						Integer fileSize = (int)fileUpload.getSize()/1024;
						
						/**
						 * 如果文件小于100M，则上传文件，否则提示用户不能超过10M
						 */
						if(fileSize<=102400){
							
							String uploadPath = "upload/"+fileName;
							File filePath = new File(request.getSession().getServletContext().getRealPath(uploadPath));

							/**
							 * 文件开始上传到服务器上
							 */	
							FileCopyUtils.copy(bytes, filePath);
							
						}else{
							System.out.println("上传的文件太大，文件大小不能超过10M");
						}
					}else{
						System.out.println("上传的文件格式不支持");
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
	       }
	}
}